<template>
  <a-table
    class="skrivet-table"
    :bordered="bordered"
    :loading="loading"
    :columns="columns"
    :data-source="list"
    :row-key="rowKey"
    table-layout="fixed"
    v-bind="$attrs"
    :pagination="false"
    :expanded-row-keys="expandedKeys"
    @expandedRowsChange="expand"
  >
    <template v-for="item in renderArr" #[item]="scope">
      <slot :name="item" :scope="scope" v-bind="scope || {}"></slot>
    </template>
  </a-table>
</template>
<script>
import { buildTree } from '@/utils/tree'
import { reactive, useSlots, toRefs } from 'vue'
export default {
  name: 'STreeTable',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: Array,
      required: false,
      default: undefined
    },
    bordered: Boolean,
    columns: {
      type: Array,
      required: false,
      default: undefined
    },
    rowKey: {
      type: [String, Function],
      default: 'id'
    },
    expandAll: {
      type: Boolean,
      default: false
    },
    initParam: {
      type: Object,
      required: false,
      default: undefined
    },
    parentKey: {
      type: [String, Function],
      default: 'parentId'
    },
    url: {
      type: String,
      required: false,
      default: undefined
    }
  },
  emits: ['change'],
  setup(props, { emit }) {
    const slots = useSlots()
    const renderArr = Object.keys(slots)
    const data = reactive({
      renderArr
    })
    return {
      ...toRefs(data)
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      expandedKeys: [],
      param: {}
    }
  },
  watch: {
    url: {
      handler: function (val, oldVal) {
        this.pullData()
      },
      immediate: true
    },
    value(val) {
      this.list = val
    }
  },
  created() {
    if (this.url) {
      Object.assign(this.param, this.initParam)
      this.pullData()
    }
  },
  methods: {
    refresh() {
      this.pullData()
    },
    expand(e) {
      this.expandedKeys = e
    },
    pullData() {
      this.expandedKeys = []
      this.loading = true
      this.$api
        .GET(this.url, this.param)
        .then((res) => {
          this.loading = false
          this.list = buildTree(res.data, this.parentKey, this.rowKey)
          this.$emit('change', this.list)
          if (this.expandAll && res.data) {
            res.data.forEach((item) => {
              this.expandedKeys.push(item[this.rowKey])
            })
          }
        })
        .catch(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style lang="less"></style>
